<?php

require_once('Smarty/Smarty.class.php');
require_once('Net/UserAgent/Mobile.php');

require_once('Okute/View/Smarty.php');
require_once('Okute/Exception.php');

/**
 * パラメータにformatがあるか確認し、ある場合は指定のformat、ない場合は自動判別するためのプラグイン。
 * formatが決まると「viewに用いるテンプレート」と「charset」が決まるためここで設定する。
 */
class Okute_Controller_Plugin_Mobile extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $session = new Zend_Session_Namespace('okute');
        $options = Zend_Registry::get('options');
        $config = $options->smarty;

        $format = null;
        if ($request->format !== null) {
            $format = $request->format;
        } else {
            if ($session->format !== null) {
                $format = $session->format;
            }
        }

        $template = null;
        if ($format) {
            if ($format === 'pc') {
                $template = $config->template_dir->pc;
            } else if ($format === 'mobile') {
                $template = $config->template_dir->mobile;
            } else {
                throw new Okute_Exception('Unknown format: pc or mobile is required. format is ' . $format);
            }
        } else {
            $format = $options->okute->display->default;
        }
        $session->format = $format;

        if ($template === null) {
            $agent = &Net_UserAgent_Mobile::singleton();
            if ($agent->isNonMobile()) {
                $template = $config->template_dir->pc;
            } else {
                $template = $config->template_dir->mobile;
            }
        }

        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
            'ViewRenderer'
        );

        $filter = Okute_View_Smarty::getOutputFilterName($config->output_charset->$format);
        Zend_Registry::set('charset', $config->output_charset->$format);

        $viewRenderer->view->setScriptPath($template);
        $viewRenderer->view->loadFilter('output', $filter);
        $viewRenderer->view->charset = $config->output_charset->$format;

        if ($options->okute->display->debug == 1) {
            $viewRenderer->view->format = $session->format;
        }
    }
}